package com.yuma.tingshu.order.template.anno;

import com.yuma.tingshu.order.template.TradeTemplate;
import com.yuma.tingshu.vo.order.OrderInfoVo;
import com.yuma.tingshu.vo.order.TradeVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TradeBeanClient implements ApplicationContextAware {
    // key:订单类型，value:订单处理于类对象
    private static final Map<String, TradeTemplate> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 根据注解获取购买的具体模板类对象
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(TradBean.class);
        if (CollectionUtils.isEmpty(beanMap)) {
            return;
        }
        // 把购买具体模板类对象放入map中
        beanMap.values().forEach(bean -> {
            // 获取bean类上的注解
            TradBean tradBean = bean.getClass().getAnnotation(TradBean.class);
            // 获取注解中的value是SystemConstant对象
            String value = tradBean.value();
            map.put(value, (TradeTemplate) bean);
        });
    }

    public OrderInfoVo trade(TradeVo tradeVo) {
        TradeTemplate tradeTemplate = map.get(tradeVo.getItemType());
        return tradeTemplate.trade(tradeVo);
    }
}
